package com.five.years.common.utils;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Component
public class SpringUtils implements ApplicationContextAware {

    private final static Logger logger = LoggerFactory.getLogger(SpringUtils.class);

    /**
     * 当前IOC
     */
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext appContext) throws BeansException {
        applicationContext = appContext;
    }

    public static ApplicationContext getApplicationContext() {
        assertContextInjected();
        return applicationContext;
    }

    /**
     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> requiredType) {
        assertContextInjected();
        return applicationContext.getBean(requiredType);
    }

    public static Object getObject(String id) {
        return applicationContext.getBean(id);
    }

    public static <T> List<T> getBeanList(Class<T> clazz) {
        assertContextInjected();
        Map<String, T> map = applicationContext.getBeansOfType(clazz);
        if (map == null || map.isEmpty()) {
            return null;
        } else {
            List<T> list = new LinkedList<>();
            list.addAll(map.values());
            return list;
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        assertContextInjected();
        return (T) applicationContext.getBean(name);
    }

    public static <T> T getObject(Class<T> requiredType) {
        return applicationContext.getBean(requiredType);
    }

    private static void assertContextInjected() {
        Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
    }

    public static String getProperties(String name) {
        assertContextInjected();
        return applicationContext.getEnvironment().getProperty(name);
    }

}
